package com.cola.action;

import com.alibaba.fastjson.JSON;
import com.cola.common.CookieConstant;
import com.cola.dao.CommonDao;
import com.cola.entity.Customer;
import com.cola.entity.User;
import com.cola.entity.WeChatInfo;
import com.cola.enums.SmsType;
import com.cola.service.CommonService;
import com.cola.service.ShopService;
import com.cola.service.UserService;
import com.cola.utils.CookieUtils;
import com.cola.utils.NonceStrUtils;
import com.cola.utils.SnowflakeIdWorker;
import com.cola.utils.Struts2Utils;
import com.cola.utils.baiduMap.BaiduMapUtils;
import com.cola.utils.baiduMap.entity.BaiduMapResult;
import com.cola.utils.jedis.JedisCacheDB;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Max
 * @since 2017/9/12
 */
public class UserAction extends BaseAction {
    private static final Logger logger = LoggerFactory.getLogger(UserAction.class);

    private String mobile;//手机号

    private String code;

    private String smsType;//短信类型

    private Integer login_type;

    private String customer_name;//店铺名
    private String city;//城市编号
    private String area;//区域编号
    private String address;//地址
    private String customer_mobile;//手机
    private String customer_contact_name;//联系人
    private String customer_img;//主照片
    private String customer_imgs;//照片
    private String channel_type_no;//渠道
    private String sms_code;

    /**
     * 跳转到登录页面
     * @author Max
     * @since 2017/9/12
     */
    public String toLogin(){
        if(login_type==null){
            login_type=-1;
        }
        switch (login_type){
            case 1:return SHOP_LOGIN;
            case 2:return MEP_LOGIN;
            default:setRequestAttribute("error_msg", "登录已经过期，请重新登录！");return LOGIN;
        }
    }


    /**
     * 店铺登录
     * @author Max
     * @since 2017/9/12
     */
    public void doShopLogin(){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("result","error");
        //登录验证
        try{
            Integer smsCheckStatus = checkSmsCodeBySmsType(mobile,code, SmsType.LOGIN_SMS.getValue());
            if(smsCheckStatus>0){
                //检查mobile 以及 openid
                User user = UserService.getInstance().getShopInfo(mobile);
                if(user!=null && user.getUserId()!=null && user.getUserId()>0){
                    //将新信息更新至用户
                    if(UserService.getInstance().updateWeChatInfo(getWeChatInfoFromRedis(),user.getUserType(),mobile)){
                        user.setWeChatInfo(getWeChatInfoFromRedis());
                        saveUserInfoToRedisCookie(user,CookieConstant.COLA_WX_ORDERING_SYSTEM_SHOP_LOGIN);
                        resultMap.put("result","success");
                    }else{
                        resultMap.put("msg","系统异常！");
                    }
                }else{
                    resultMap.put("msg","该手机号未注册！");
                }
            }else{
                resultMap.put("msg","验证码错误！");
            }
        }catch (Exception e){
            logger.error("店铺登录异常！",e);
            resultMap.put("msg","登录异常！");
        }

        Struts2Utils.renderJson(resultMap);
    }

    /**
     * 经销商/配送员登录
     * @return
     * @author Max
     * @since 2017/9/12
     */
    public void doMepLogin(){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("result","error");
        try{
            //登录验证
            Integer smsCheckStatus = checkSmsCodeBySmsType(mobile,code, SmsType.LOGIN_SMS.getValue());
            if(smsCheckStatus>0){
                //检查mobile 以及 openid
                User user = UserService.getInstance().getMepInfo(mobile);
                if(user!=null){
                    //将微信信息更新至用户
                    if(UserService.getInstance().updateWeChatInfo(getWeChatInfoFromRedis(),user.getUserType(),mobile)){
                        user.setWeChatInfo(getWeChatInfoFromRedis());
                        saveUserInfoToRedisCookie(user,CookieConstant.COLA_WX_ORDERING_SYSTEM_MEP_LOGIN);
                        resultMap.put("result","success");
                    }else{
                        resultMap.put("msg","系统异常！");
                    }
                }else{
                    resultMap.put("msg","该手机号未注册！");
                }
            }else{
                resultMap.put("msg","验证码错误！");
            }
        } catch (Exception e){
        logger.error("经销商/配送员登录！",e);
        resultMap.put("msg","登录异常！");
        }
        Struts2Utils.renderJson(resultMap);
    }

    /**
     * 跳转到店铺注册页面
     * @author Max
     * @since 2017/9/20
     */
    public String toRegisterShop(){

        setRequestAttribute("cityAreaList", CommonService.getInstance().getCityAreaList());

        setRequestAttribute("channelList", CommonService.getInstance().getChannelList());
        return SUCCESS;
    }


    /**
     * 店铺注册
     * @author Max
     * @since 2017/9/14
     */
    public void registerShop(){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("result","error");
        WeChatInfo weChatInfo = getWeChatInfoFromRedis();
        //登录验证
        Integer smsCheckStatus = checkSmsCodeBySmsType(customer_mobile,sms_code, SmsType.REGISTER_SMS.getValue());
        if(smsCheckStatus>0){
            //检查手机号是否绑定
            if(!UserService.getInstance().checkMobile(customer_mobile)){
                Customer customer = new Customer();
                customer.setCustomer_name(customer_name);
                customer.setCity(city);
                customer.setAddress(address);
                customer.setArea(area);
                customer.setCustomer_mobile(customer_mobile);
                customer.setCustomer_contact_name(customer_contact_name);
                customer.setCustomer_img(customer_img);
                List<String> list = new ArrayList<>();
                list.add(customer_img);
                customer.setCustomer_imgs(JSON.toJSONString(list));
                customer.setChannel_type_no(channel_type_no);
                customer.setCustomer_wechat_nick(weChatInfo.getNickname());
                customer.setCustomer_open_id(weChatInfo.getOpenid());
                customer.setCustomer_head_img_url(weChatInfo.getHeadimgurl());
                SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1,1);
                customer.setCustomer_system_no(snowflakeIdWorker.nextId()+"");
                //插入信息表
                String city = CommonDao.getInstance().getAreaNameByNo(customer.getCity());
//                BaiduMapResult result = BaiduMapUtils.getLocationInfoByAddress(city+customer.getAddress());
//                if(result!=null) {
//                    customer.setCustomer_lat(result.getResult().getLocation().getLat().doubleValue());
//                    customer.setCustomer_lng(result.getResult().getLocation().getLng().doubleValue());
//                }
                if(ShopService.getInstance().saveShopInfo(customer)){
                    resultMap.put("result","success");
                }

            }else{
                resultMap.put("msg","手机号已被注册！");
            }
        }else{
            resultMap.put("msg","验证码错误！");
        }
        Struts2Utils.renderJson(resultMap);
    }

    /**
     * 发送验证码
     * @author Max
     * @since 2017/9/13
     */
    public void sendSmsCode(){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("result","error");
        String code = NonceStrUtils.generateNumStr(4);
        //将验证码Key信息存入Cookie;
        String cookieKey = getCookieKeyBySmsType(smsType);
        if(StringUtils.isNotEmpty(cookieKey)) {
            //获取RedisKey
            String redisKey = smsType + mobile + NonceStrUtils.generateCommonStr(10);
            String redisValue = mobile + code;
            logger.info("手机验证码为:【"+code+"】,手机号为:【"+mobile+"】");
            //发送验证码
            //将信息存入Cookie
            boolean a = CookieUtils.setCookie(getResponse(), cookieKey, redisKey, 180);
            //将信息存入Redis
            boolean b = JedisCacheDB.saveObject(redisKey, redisValue, 180);
            if(a && b){
                resultMap.put("result","success");
            }
        }
        Struts2Utils.renderJson(resultMap);
    }

    /**
     * 检查验证码是否正确
     * @param mobile 手机号
     * @param code 验证码
     * @param smsType 验证码类型
     * @author Max
     * @return 1:正确 -1：错误 -2:过期
     * @since 2017/9/13
     */
    private Integer checkSmsCodeBySmsType(String mobile,String code,String smsType){
        String cookieKey = getCookieKeyBySmsType(smsType);

        String redisKey = CookieUtils.getCookieValue(getRequest(),cookieKey);

        if(StringUtils.isNotEmpty(redisKey)){
            Object temp = JedisCacheDB.getObject(redisKey);
            if(temp==null){
                return -2;
            }
            if((mobile+code).equals(temp)){
                return 1;
            }else{
                return -1;
            }
        }else{
            return -2;
        }
    }


    /**
     * 根据验证码类型获取CookieKey
     * @param smsType
     * @return 
     * @author Max
     * @since 2017/9/13
     */
    private String getCookieKeyBySmsType(String smsType){
        switch (smsType){
            case "login_sms":return CookieConstant.COLA_WX_ORDERING_SYSTEM_LOGIN_SMS;
            case "register_sms":return CookieConstant.COLA_WX_ORDERING_SYSTEM_REGISTER_SMS;
            case "reset_sms":return CookieConstant.COLA_WX_ORDERING_SYSTEM_RESET_SMS;
        }
        return null;
    }

    /**
     * 退出登录
     * @author Max
     * @since 2017/9/18
     */
    public void loginOut(){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("result","error");
        if(emptyUserInfo()){
            resultMap.put("result","success");
        }
        Struts2Utils.renderJson(resultMap);
    }



    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getSmsType() {
        return smsType;
    }

    public void setSmsType(String smsType) {
        this.smsType = smsType;
    }

    public Integer getLogin_type() {
        return login_type;
    }

    public void setLogin_type(Integer login_type) {
        this.login_type = login_type;
    }

    public static Logger getLogger() {
        return logger;
    }

    public String getCustomer_name() {
        return customer_name;
    }

    public void setCustomer_name(String customer_name) {
        this.customer_name = customer_name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCustomer_mobile() {
        return customer_mobile;
    }

    public void setCustomer_mobile(String customer_mobile) {
        this.customer_mobile = customer_mobile;
    }

    public String getCustomer_contact_name() {
        return customer_contact_name;
    }

    public void setCustomer_contact_name(String customer_contact_name) {
        this.customer_contact_name = customer_contact_name;
    }

    public String getCustomer_img() {
        return customer_img;
    }

    public void setCustomer_img(String customer_img) {
        this.customer_img = customer_img;
    }

    public String getCustomer_imgs() {
        return customer_imgs;
    }

    public void setCustomer_imgs(String customer_imgs) {
        this.customer_imgs = customer_imgs;
    }

    public String getChannel_type_no() {
        return channel_type_no;
    }

    public void setChannel_type_no(String channel_type_no) {
        this.channel_type_no = channel_type_no;
    }


    public String getSms_code() {
        return sms_code;
    }

    public void setSms_code(String sms_code) {
        this.sms_code = sms_code;
    }
}
